<template>
	<view>

		<!-- <view style="margin-bottom:30rpx;">
			<map style="width: 100%; height: 300px;" :scale="16" :enable-zoom="true" :latitude="map.center_lat" :longitude="map.center_lng" :markers="markers">
							</map>

		</view> -->
		<view class="search-box">
			<input type="input" placeholder="搜店名" v-model="keyword"><span></span>
		</view>
		<view>
			<view style="display: flex; align-items: center;padding: 30rpx;">
				<view style="flex:1;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;font-size: 24rpx;font-weight: 600;" @click="centerMyLocation"><u-icon name="map-fill"></u-icon> {{currentLocation.addr}}</view>
				<view style="width: 3em;text-align: center;color:rgba(0,0,0,.6)" @click="getMyLocation">刷新</view>
				<view style="width: 5em;text-align: center;color:rgba(0,0,0,.6)" @click="openPage('/pages/stores/map')">查看地图</view>
			</view>

			<!-- <ul class="tag-list">
				<li :class="{'active':attr===''}" @click="attr=''">全部</li>
				<li :class="{'active':attr==='gas_station'}" @click="attr='gas_station'">加油站</li>
				<li :class="{'active':attr==='wash_car'}" @click="attr='wash_car'">洗车店</li>
				<li :class="{'active':attr==='maintenance'}" @click="attr='maintenance'">保养店</li>
				<li :class="{'active':attr==='repair_car'}" @click="attr='repair_car'">汽修厂</li>
				<li :class="{'active':attr==='s4'}" @click="attr='s4'">4S店</li>
				<li :class="{'active':attr==='pickup'}" @click="attr='pickup'">自提点</li>
				<li :class="{'active':attr==='inspection'}" @click="attr='inspection'">检测站</li>
			</ul> -->
		</view>
		<!-- <view>Search bar</view> -->
		<view class="wrap u-p-l-30 u-p-r-30">
			<u-row gutter="1" v-for="(item,index) in filteredStores" class="table-row" style="background-color: #f6f6f6;padding-top:0; border-radius: 10rpx;margin-bottom: 20rpx;">
				<u-col :span="12" style="display: flex;padding: 20rpx;align-items: flex-start;" class="u-line-1" @click="openPage('/pages/stores/detail',{id:item.id})">
					<view>
						<u-image :src="item.cover" width="120rpx" height="120rpx" mode="aspectFill"></u-image>
					</view>
					<view style="flex:1;overflow: hidden;padding-left:20rpx;">
						<view class="store-title" style="font-size: 1.2em;line-height:1.5;margin-bottom:10rpx;font-weight:800;word-wrap:break-word;overflow-wrap:break-word;white-space: normal;" @click="centerShop(item)">{{item.shop_name}}</view>
						<view class="store-addr u-font-xs" style="margin-bottom: 10rpx;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">{{item.address}}</view>
						<view class="rating-distance u-font-xs" style="display: flex;align-items: center;justify-content: space-between;">
							<view class="rating"><u-icon name="star-fill" style="color:red;"></u-icon> <span style="color:red;padding:0 10rpx;">{{item.rating}}</span></view>
							<view class="distance" @click="openLocation(item)">{{showDistance(item)}}<!-- <u-icon name="arrow-right"></u-icon> --></view>
						</view>
					</view>
				</u-col>
				<u-col>
					<template v-for="product in item.products">
						<view style="display:flex;border: 1px solid #ccc;margin-bottom: 10rpx;padding: 10rpx;border-radius: 8rpx;">
							<view class="product-name" style="width: 320rpx;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">{{product.item_name}}</view>
							<view class="price" style="display:flex; flex:1; padding-left: 10rpx;">
								<view style="color: red;margin-right: 20rpx;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" v-if="product.unit_price>0">¥ {{parseFloat(product.unit_price).toFixed(0)}}</view>
								<view style="text-decoration: line-through;color: gray;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" v-if="product.original_price>0">¥ {{parseFloat(product.original_price).toFixed(0)}}</view>
							</view>
							<view class="icon-cart" @click="openPage('/pages/buy/item',{id:product.item_id})" style="color:red; border: 1px solid red; border-radius: 50%; width: 40rpx; height: 40rpx;display:flex; align-item:center;justify-content: center;"><u-icon name="shopping-cart-fill"></u-icon></view>
						</view>
					</template>
				</u-col>

			</u-row>

			<u-loadmore class="u-padding-30" :status="loadStatus" @loadmore="loadMore"
				:load-text="loadText" v-if="stores.length>0"></u-loadmore>
			<u-back-top :scroll-top="scrollTop"></u-back-top>

		</view>
		<wx-share :title='shop.name' :desc="shop.store_introduction" :imgUrl="shop.cover" link="/" ref="wxs"></wx-share>
		<custom-tabbar></custom-tabbar>
	</view>
</template>

<script>
	var jweixin = require('jweixin-module')
	export default {
		data() {
			return {
				scrollTop: 0,
				stores: [],
				user: {},
				paging: {
					current_page: 1,
					total_pages: 1,
					page_zie: 1000,
					type:'official,third'
				},
				loadStatus: 'loadmore',
				loadText: {
					loadmore: '加载更多',
					loading: '努力加载中',
					nomore: '没有更多了'
				},
				keyword:'',
				attr:'',
				shop:{},
				location_img: '../../static/images/location.png',
				map:{
					center_lat:'',
					center_lng:''
				},
				currentLocation:{
					lat:'',
					lng:'',
					addr:'待定位...'
				}
			}
		},
		computed:{
			markers(){
				let covers = []
				if(this.filteredStores.length>0){
					for(let i=0;i<this.filteredStores.length;i++){
						let loc = {
							latitude: parseFloat(this.filteredStores[i].lat),
							longitude: parseFloat(this.filteredStores[i].lng),
							iconPath: this.location_img,
							title: this.filteredStores[i].shop_name
						}
						covers.push(loc)
					}
				}
				return covers;
			},
			filteredStores(){
				let filteredStores = this.stores
				if(this.attr){
					if(this.attr==='gas_station'){
						filteredStores = this.stores.filter(store => store.is_gas_station==='yes')
					}else if(this.attr==='wash_car'){
						filteredStores = this.stores.filter(store => store.is_wash_car==='yes')
					}else if(this.attr==='repair_car'){
						filteredStores = this.stores.filter(store => store.is_repair_car==='yes')
					}else if(this.attr==='s4'){
						filteredStores = this.stores.filter(store => store.is_s4==='yes')
					}else if(this.attr==='maintenance'){
						filteredStores = this.stores.filter(store => store.is_maintenance==='yes')
					}else if(this.attr === 'pickup'){
						filteredStores = this.stores.filter(store => store.is_pickup==='yes')
					}else if(this.attr==='inspection'){
						filteredStores = this.stores.filter(store => store.is_inspection==='yes')
					}
				}
				if(this.keyword){
					filteredStores = filteredStores.filter(store => store.shop_name.includes(this.keyword))
				}
				return filteredStores
			}
		},
		onLoad() {
			this.getShop()
			this.setWxShare()
			this.getMyLocation()
		},
		onShow() {
			this.getUserInfo();
			this.getLogList();
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		onReachBottom() {
			if (this.paging.current_page >= this.paging.total_pages) {
				this.loadStatus = 'nomore';
				return;
			}
			this.loadStatus = 'loading';
			this.paging.current_page = ++this.paging.current_page;
			this.getLogList();
		},
		onPullDownRefresh(){
			this.paging.current_page = 1
			this.getLogList()
		},
		methods: {
			getMyLocation(){
				console.log('get-location')
				uni.getLocation({
					type: 'gcj02',
					success: (res)=> {
						this.currentLocation.lng = res.longitude
						this.currentLocation.lat = res.latitude
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						// console.log(res)
						let location = res.latitude+','+res.longitude
						this.currentLocation.addr = '获取中...'
						this.$u.get('/shopping/get-address?location='+location, {}).then(res => {
							// console.log(res)
							this.currentLocation.addr = res
							this.map.center_lng = parseFloat(this.currentLocation.lng)
							this.map.center_lat = parseFloat(this.currentLocation.lat)
							this.sortStores()
						}).catch(e => {
							console.log(e)
						})
					}
				});
			},
			sortStores(){
				if(this.stores.length>0 && this.currentLocation.lat>0 && this.currentLocation.lng>0){
					this.stores.forEach(store=>{
						this.computeDistance(store)
					})
					this.stores.sort((a, b) => a.distance - b.distance);
				}
			},
			getDistanceInKm(lat1, lon1, lat2, lon2) {
			  const earthRadiusKm = 6371; // 地球半径，单位：千米
			  // 将经纬度转换为弧度
			  const dLat = this.toRadians(lat2 - lat1);
			  const dLon = this.toRadians(lon2 - lon1);
			  // 应用 Haversine 公式计算距离
			  const a =
			    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
			    Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
			    Math.sin(dLon / 2) * Math.sin(dLon / 2);
			  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
			  let distance = earthRadiusKm * c;

				if(distance>1){
					return distance.toFixed(1)+'km'
				}
				if(distance>0){
					return (distance*1000).toFixed(0)+'m'
				}
				return '未知'
			},
			computeDistance(store){
				if(store.lat>0 && store.lng>0 && this.currentLocation.lat>0 && this.currentLocation.lng>0){
					const earthRadiusKm = 6371; // 地球半径，单位：千米
					// 将经纬度转换为弧度
					const dLat = this.toRadians(store.lat - this.currentLocation.lat);
					const dLon = this.toRadians(store.lng - this.currentLocation.lng);
					// 应用 Haversine 公式计算距离
					const a =
					  Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					  Math.cos(this.toRadians(this.currentLocation.lat)) * Math.cos(this.toRadians(store.lat)) *
					  Math.sin(dLon / 2) * Math.sin(dLon / 2);
					const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
					let distance = earthRadiusKm * c;
					store.distance = distance
				} else {
					return store.distance = 999999;
				}
			},
			toRadians(degrees) {
			  // 将角度转换为弧度
			  return degrees * (Math.PI / 180);
			},
			showDistance(store){
				if(!store.lat || store.lat<0){
					return '定位失败'
				}
				if(!this.currentLocation.lat){
					return '定位中'
				}
				return this.getDistanceInKm(this.currentLocation.lat,this.currentLocation.lng,store.lat,store.lng)
			},
			getShop() {
				this.$u.post('/shopping/shop-setting', {}).then(res => {
					this.shop = res;
					this.map.center_lng = parseFloat(this.shop.lng)
					this.map.center_lat = parseFloat(this.shop.lat)
				}).catch(e => {

				})
			},
			centerShop(shop){
				// 将这个店移到地图中心
				this.map.center_lng = parseFloat(shop.lng)
				this.map.center_lat = parseFloat(shop.lat)
			},
			centerMyLocation(){
				if(this.currentLocation.lat){
					this.map.center_lng = parseFloat(this.currentLocation.lng)
					this.map.center_lat = parseFloat(this.currentLocation.lat)
				}
			},
			getUserInfo() {
				this.$u.post('/user/info', {}).then(res => {
					this.user = res;
					if (this.user.referral_id == 0) {
						this.user.referral_id = '';
					}
				}).catch(e => {
					console.log(e)
				})
			},
			openPage(jumpURL, params = {}) {
				this.$u.route({
					type: 'to',
					params: params,
					url: jumpURL,
					animationType: 'slide-in-bottom'
				});
			},
			getLogList() {
				this.$u.post('/store/list', this.paging).then(res => {
					if (res.page.current_page === 1) {
						this.stores = res.list;
					} else {
						this.stores = this.stores.concat(res.list)
					}
					this.paging.current_page = res.page.current_page;
					this.paging.total_pages = res.page.total_pages;
					this.paging.page_size = res.page.page_size;
					this.sortStores()
					uni.stopPullDownRefresh()
				}).catch(e => {
					console.log(e)
				})
			},
			loadMore() {
				console.log('load more')
				if (this.paging.current_page < this.paging.total_pages) {
					this.paging.current_page = this.paging.current_page + 1;
					this.getLogList();
				}
			},
			openLocation(store){
				console.log(store)
				jweixin.ready(() => {
				  jweixin.openLocation({
				    latitude: parseFloat(store.lat),
				    longitude: parseFloat(store.lng),
				    name: store.shop_name,
					address: store.address,
				    scale: 18,
				    fail: (res) => {
				      console.log(res);
				    }
				  })
				})
			},
			setWxShare() {
				let that = this;
				this.$u.post('/shopping/wx-js-sdk-config', {
					current_page: location.href.split('#')[0]
				}).then(res => {
					console.log(res)
					jweixin.config(res);
					jweixin.ready(function() {
						console.log('wx-is ready')
					});
					jweixin.error(function(res) {
						console.log('wx-is error')
						console.log(res)
						// config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
					});
				}).catch(e => {

				})
			}
		}
	}
</script>

<style>
	.demo-layout {
		padding: 10rpx;
		box-sizing: border-box;
	}

	.demo-layout.u-font-xs {
		padding-top: 0;
		color: #8F8F94;
	}
	.demo-layout.green{
		color: #328a44;
	}
	.demo-layout.red{
		color:red;
	}

	.table-title {
		font-weight: 400;
		border-bottom: 1px solid #DDD;
		background-color: #FFF;
		padding: 18rpx 0;
	}

	.table-row {
		border-bottom: 1px dotted #DDD;
	}

	.tag-list{
		text-decoration: none;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding-inline-start: 0;
		padding: 0 30rpx;
		box-sizing: border-box;
	}
	.tag-list li{
		flex: 0 0 23%;
		margin-bottom: 20rpx;
		border: 1px solid rgba(0,0,0,.63);
		border-radius: 10rpx;
		text-decoration: none;
		list-style: none;
		display: inline-block;
		text-align: center;
		font-size: 24rpx;
	}
	.tag-list li.active{
		color: red;
		border-color: red;
	}
	.search-box{
		padding: 0 30rpx;
		box-sizing: border-box;
		/* margin-bottom: 20rpx; */
		margin-top:20rpx;
		position:sticky;
		top:0;
		z-index:999;
	}
	.search-box input{
		background-color: #eee;
		padding: 15rpx 30rpx;
		padding-right: 50rpx;
		border-radius: 50rpx;
		overflow: hidden;
		font-size: 24rpx;
	}
</style>
